package org.grow.infru.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: xwg
 * @CreateDate: 2021/11/5
 */

@Service
@Scope("prototype")
public class CodeGene {
    public static final String redisCodePre = "CODE:";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public String nextCode(String businessPrefix) {

        String date = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        Integer r = ThreadLocalRandom.current().nextInt(8999) + 1000;
//        String icrePart = "00001";
        String icrePart = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        String targetKey = redisCodePre + businessPrefix;
//        可以设置过期时间
        ops.setIfAbsent(targetKey, 1 + "");
//        redis
        String s = ops.get(targetKey);
        ops.increment(targetKey);

        String format = String.format("%05d", Integer.parseInt(s));
        icrePart = format.substring(format.length() - 5);

        StringBuffer stringBuffer = new StringBuffer();
        String code = stringBuffer.append(businessPrefix)
                .append(date)
                .append(r)
                .append(icrePart)
                .toString();
        return code;
    }
}
